package storageManager;

import java.io.IOException;

public class Tools {//This class has the methods that my program uses frequently
	public static int comparator(String s1,String s2){//This method compares the given string in the wanted format
		if(isNumeric(s1)&&isNumeric(s2))
			return (int) Math.ceil(Double.parseDouble(s1)-Double.parseDouble(s2));//If keyValues is numeric than it compares them as doubles
		else if(isNumeric(s1)&&!isNumeric(s2))
			return -1;
		else if(!isNumeric(s1)&&isNumeric(s2))
			return 1;
		else
			return s1.compareTo(s2);
	}
	public static boolean isNumeric(String s){//Returns true if the given string is made of numeric characters
		try{
			double d = Double.parseDouble(s);
		}catch(NumberFormatException nfe){
			return false;
		}
		return true;
	}
	public static byte[] stringToByte(String s,int size){//This method takes a string and an integer.
		byte[] stringInByte = new byte[size];//First creates a byte array with the given integer
		for(int i=0; i<s.length(); i++){
			stringInByte[i] = (byte) s.charAt(i);//Fills the array with the byte values of the characters in the given string
		}
		return stringInByte;//returns the byte array
	}
	public static String byteToString(byte[] b){//Takes a byte array as a parameter and transforms it into a String and returns the string
		String result = "";
		for(int i=0; i<b.length; i++){
			if(b[i] != 0){
				result += (char)b[i];
			}
		}
		return result;
	}
	public static String byteToString(byte[] source, int sPos, int length){//This method takes a byte array and and transform the specified part of it to string. 
		String result = "";
		for(int i=sPos; i<sPos+length; i++){
			if(source[i] != 0){
				result += (char)source[i];
			}
		}
		return result;//Transform the bytes in byte array starting from the given index until the given length, into a string and returns it.
	}
	public static boolean isASCII(String s){//This method checks if a string has non-ascii character
		char[] letters = s.toCharArray();
		for(char c : letters){
			if( c>127)
				return false;
		}
		return true;
	}
	public static boolean checkTheName(int upperLimit,String name,String indicator){//This methods check if the string consist ascii characters and shorter than the given upperlimit.
		if(!Tools.isASCII(name)){
			System.out.println("A "+indicator+" cannot contain any non-ASCII character!");
			return false;
		}			
		else if(name.length()>upperLimit){
			System.out.println("A "+indicator+" cannot have a greater length than it has decided while creating the table!");	
			return false;
		}
		return true;
	}
}
